
/*
缓存图片方法
传入图片网络地址，先检测本地缓存中是否存在同名文件，而后请求网络下载图片
*/

//创建下载
function getCacheImage (url){
	if(!url || typeof url !== 'string'){
		return new Promise((resolve, reject)=>{reject({code: 0, msg: '图片地址不存在', data: url})})
	}
	if(/^http/.test(url)){
		let filename = '_doc/'
		filename += url.split('/').slice(-1).join()
		return new Promise (function(resolve, reject){
			plus.io.resolveLocalFileSystemURL(filename, function( entry ) {
				let path = plus.io.convertLocalFileSystemURL(filename);
				path = 'file://' + path
				resolve({code: 1, msg: '缓存读取成功', data: path})
			}, function(){
				createDownload(url, function(path){
					//resolve({code: 1, msg: '图片下载成功', data: path})
				})
				resolve({code: 1, msg: '首次返回原始图片', data: url})
			})
		})
	}else{
		return new Promise((resolve, reject)=>{reject({code: 0, msg: '图片地址错误', data: url})})
	}
}

//下载图片
function createDownload(url) {
	let filename = '_doc/'
	filename += url.split('/').slice(-1).join()
	let dtask = plus.downloader.createDownload(url, {
		filename: filename
	}, function(d, status){
		if(status == 200){
			let path = plus.io.convertLocalFileSystemURL(d.filename);
			path = 'file://' + path
			//success(path)
		}else{
			//success({code: 0, msg: '图片下载失败', data: url})
		}  
	});
	dtask.start(); 
}

var clearFile = function (path){
	return new Promise(function(resolve, reject){
		plus.io.resolveLocalFileSystemURL(path, function(entry) {
			entry.removeRecursively(function(entry) {
				resolve({code: 1, msg: 'ok'})
			}, function ( e ) {
				resolve({code: 1, msg: 'err'})
			})
		}, function(e){
			console.log('文件不存在')
		})
	})
}

//清除所有缓存文件
const clearCacheFile = async function (callback){
	await clearFile('_doc/')
	await clearFile('_downloads/')
	callback && (callback())
}

export {getCacheImage, clearCacheFile}

